/**
 * @description 工具栏：查询组件
 * @author chenyan
 */

import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, Tabs, Row, Col } from 'antd';
import { FirstHeaderC, QuickQueryC, TableC, SecondHeaderC, NoDataC, CandlestickChartsC } from '../../../../../comps';
import TradeTableC from './tradeTableC';
import Charts from './pointCharts';
import style from './index.less';

const { TabPane } = Tabs;

@Form.create()
class BondArtificialTradesC extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      bondID: '', // 债券id
      currentPage: 1, // 当前页码
      numInPage: 3000, // 每页条数
      dateRange: '0', // 0 近三个月  1 近1年
      activeKey: '', // 当前tab页的key
    };
  }

  componentDidMount() {
    this.setState(
      {
        bondID: this.props.bondID,
      },
      () => {
        // 更新tab的key值
        const bondInfo = JSON.parse(sessionStorage.getItem('bondInfo'));
        this.setState({
          activeKey: bondInfo.type ? bondInfo.type : '中债',
        });
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    // 判断是否是最新的bondID
    if (nextProps.bondID && nextProps.bondID != this.state.bondID) {
      this.setState(
        {
          bondID: nextProps.bondID,
        },
        () => {
          // 更新tab的key值
          const bondInfo = JSON.parse(sessionStorage.getItem('bondInfo'));
          this.setState({
            activeKey: bondInfo.type,
          });
          this.queryData();
        },
      );
    }
  }

  // 页面销毁去缓存
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'bondArtificialTradesM/setState',
      payload: {
        historyDataObj: {}, // 历史行情数据
        xAxis: [], // 信用债 点状图x轴
        series: [], // 信用债  点状图y轴
        kLineChartsData: [], // 利率债  k线图数据
        zzhaiTableDataObj: {}, // 中债表格数据
        zzhengTableDataObj: {}, // 中债表格数据
        shqTableDataObj: {}, // 上清表格数据
      },
    });
  }

  // 查询历史行情echarts 及表格数据
  queryData = () => {
    const { bondID, currentPage, numInPage, dateRange } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'bondArtificialTradesM/getHistorical',
      payload: {
        bondID,
        dateRange,
        currentPage,
        numInPage,
      },
    });
  };

  // 三个月/一年按钮切换
  showTimeChange = (e) => {
    this.setState(
      {
        dateRange: e,
      },
      () => {
        if (!this.state.bondID) return; // 避免初始化赋值时自动请求
        this.queryData();
        this.firstChild && this.firstChild.queryTableData(); // 时间按钮变更子组件数据重新请求
        this.secChild && this.secChild.queryTableData();
        this.thirdChild && this.thirdChild.queryTableData();
      },
    );
  };

  renderTable = () => {
    const {
      bondArtificialTradesM: {
        historyDataObj: { bondType, result = {} },
      },
    } = this.props;
    const { columns = [], dataSource = [] } = result;
    if (bondType == 0) {
      // 债券类型：0-利率债 1-信用债
      columns.map((item) => {
        if (item.key != 'date') {
          item.width = `${parseFloat(87 / (columns.length - 1))}%`;
          item.type = 'money';
          item.toFixed = 4;
          if (item.key == 'volume') {
            item.type = 'number';
          }
        }
      });
    } else {
      columns.map((item) => {
        if (item.key != 'date') {
          item.width = `${parseFloat(86 / (columns.length - 1))}%`;
        }
        if (item.key != 'date' && item.key != 'transactionTime' && item.key != 'tradingMarket') {
          item.type = 'number';
          if (item.key == 'price' || item.key == 'amount') {
            item.type = 'money';
          }
        }
        if (item.key == 'transactionTime') {
          item.render = (text) => {
            return text.substr(0, text.indexOf('.'));
          };
        }
      });
    }
    return (
      <div>
        <TableC
          columns={columns}
          dataSource={dataSource}
          scroll={dataSource.length > 8 ? { y: 260 } : {}} // 大于8行滚动
          hidePage={true}
          rowKey='key'
        />
      </div>
    );
  };

  // tab切换更新key
  handleChangeTab = (e) => {
    this.setState({
      activeKey: e,
    });
  };

  render() {
    const { loading } = this.props;
    const {
      bondID,
      bondArtificialTradesM: { historyDataObj, xAxis, echartsData, min, max, kLineChartsData, zzhaiTableDataObj, zzhengTableDataObj, shqTableDataObj },
    } = this.props;
    const { activeKey, dateRange } = this.state;

    return (
      <div className={style.bondArtificiakTrade}>
        <FirstHeaderC title={historyDataObj.bondName || ''} />
        <Row type='flex'>
          <Col span={12} className={style.sec_title}>
            <SecondHeaderC title='历史行情' />
          </Col>
          <Col span={12}>
            <div className={style.right}>
              <QuickQueryC
                dataSource={[
                  { value: '0', title: '近三个月' },
                  { value: '1', title: '近一年' },
                ]}
                initialValue={'0'}
                onChange={(e) => this.showTimeChange(e)}
              />
            </div>
          </Col>
        </Row>
        <Spin spinning={loading.effects['bondArtificialTradesM/getHistorical'] == true}>
          <Row>
            <Col span={24}>
              {historyDataObj.bondType && historyDataObj.bondType === '0' ? (
                <div style={{ marginBottom: '10px' }}>
                  <CandlestickChartsC height={400} data={kLineChartsData} />
                </div>
              ) : echartsData.length && xAxis.length ? (
                <Charts data={echartsData} xAxis={xAxis} min={min} max={max} />
              ) : (
                <div style={{ marginBottom: '10px' }}>
                  <NoDataC />
                </div>
              )}
            </Col>
          </Row>
          {this.renderTable()}
        </Spin>
        <div style={{ marginTop: '23px' }} className={style.sec_title}>
          <SecondHeaderC title='异常交易记录' />
        </div>

        <Tabs activeKey={activeKey} onChange={this.handleChangeTab}>
          <TabPane tab='中债' key='中债' forceRender={false}>
            <TradeTableC
              type={0}
              activeKey={activeKey}
              onRef={(ref) => {
                this.firstChild = ref;
              }}
              bondID={bondID}
              dateRange={dateRange}
              columns={zzhaiTableDataObj.columns || []}
              dataSource={zzhaiTableDataObj.dataSource || []}
              total={zzhaiTableDataObj.pageInfo ? zzhaiTableDataObj.pageInfo.total || 0 : 0}
            />
          </TabPane>
          <TabPane tab='上清' key='上清' forceRender={false}>
            <TradeTableC
              type={1}
              activeKey={activeKey}
              onRef={(ref) => {
                this.secChild = ref;
              }}
              bondID={bondID}
              dateRange={dateRange}
              columns={shqTableDataObj.columns || []}
              dataSource={shqTableDataObj.dataSource || []}
              total={shqTableDataObj.pageInfo ? shqTableDataObj.pageInfo.total || 0 : 0}
            />
          </TabPane>
          <TabPane tab='中证' key='中证' forceRender={false}>
            <TradeTableC
              type={2}
              activeKey={activeKey}
              onRef={(ref) => {
                this.thirdChild = ref;
              }}
              bondID={bondID}
              dateRange={dateRange}
              columns={zzhengTableDataObj.columns || []}
              dataSource={zzhengTableDataObj.dataSource || []}
              total={zzhengTableDataObj.pageInfo ? zzhengTableDataObj.pageInfo.total || 0 : 0}
            />
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

export default connect(({ bondArtificialTradesM, loading }) => ({
  bondArtificialTradesM,
  loading,
}))(BondArtificialTradesC);
